<template>
	<view class="file_download">
		<div style="margin-top: 10px">下载中...</div>
	</view>
</template>
<script>
	import {
		Api
	} from '@/utils/Api'
	export default {
		props: {},
		data() {
			return {
				fileList: []
			}
		},
		onLoad: function(options) {
			let that = this
			let url = decodeURIComponent(options.url) // 解码
			let p = url.lastIndexOf('../');
			if (p != -1) {
				url = url.substring(p + 2);
			}
			if (url.indexOf('/') != 0) {
				url = '/' + url
			}
			let baseUrl = Api.baseUrl;
			url = baseUrl + url;
			console.log(url);
			wx.showLoading({
				title: '加载中...',
			})
			wx.downloadFile({ // 下载文件
				url: url,
				success: function(res) {
					wx.saveFile({
						tempFilePath: res.tempFilePath,
						success(res) {
							let filePath = res.savedFilePath // 存放的路径
							wx.showToast({
								title: '保存成功：' + filePath,
								icon: 'none'
							})
							
							wx.openDocument({ // 预览文件
							  filePath: filePath,
							  showMenu: true,
							  success: function (res) {
								setTimeout(() => {
									wx.hideLoading({
										success: (res) => {
											wx.navigateBack({
												delta: 1,
											})
										},
									})
								}, 1500);
							  },
							  fail: function (error) {
							    console.log(error);
								wx.showToast({
									title: error,
									icon: 'error'
								})
								setTimeout(() => {
									wx.hideLoading({
										success: (res) => {
											wx.navigateBack({
												delta: 1,
											})
										},
									})
								}, 1500);
							  }
							})
						},
						fail(error) {
							wx.showToast({
								title: '文件下载失败',
								icon: 'error'
							})
						}
					})
				},
				fail: function(error) {
					console.log(error);
					wx.showToast({
						title: '文件下载失败',
						icon: 'error'
					})
					wx.hideLoading()
				}
			})
		},
		methods: {
		}
	}
</script>

<style lang="scss" scoped>
	.file_download {
		width: 100%;
	}
</style>